package cn.rslee.server;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * 描述：
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID   DATE                    PERSON          REASON
 *  1    2016年3月21日         rslee               Create
 * ****************************************************************************
 * </pre>
 * 
 * @author rslee
 * @since 1.0
 */
public class GlobalPropertiesListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent e) {
	}

	@Override
	public void contextInitialized(ServletContextEvent e) {
		ServletContext context = e.getServletContext();
		String systemConfigLocation = context
				.getInitParameter("systemConfigLocation");

		InputStream in = null;

		if (systemConfigLocation != null
				&& systemConfigLocation.startsWith("classpath:")) {
			in = GlobalPropertiesListener.class
					.getResourceAsStream(systemConfigLocation.replace(
							"classpath:", "/"));
		} else {
			try {
				in = new FileInputStream(systemConfigLocation);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}

		Properties p = new Properties();
		try {
			p.load(in);

			for (Object key : p.keySet()) {
				context.setAttribute(key.toString(), p.get(key));
			}

			context.setAttribute("aaa", "xxxxx");

		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	public static void main(String[] args) {

		InputStream in = GlobalPropertiesListener.class
				.getResourceAsStream("/config.properties");

		Properties p = new Properties();

		try {
			p.load(in);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

}
